/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
  DefaultFooter,
} from '@ant-design/pro-layout';
import React, { useEffect, useState } from 'react';
import { Link, useIntl, connect, Dispatch,history } from 'umi';
import { GithubOutlined } from '@ant-design/icons';
import { Result, Button, Tabs } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { ConnectState } from '@/models/connect';
import { getAuthorityFromRouter } from '@/utils/utils';
import logo from '../assets/logo.svg';
import { Route } from 'react-router-dom';

// import routes from  '../../config/routes';

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">Go Login</Link>
      </Button>
    }
  />
);

const { TabPane } = Tabs;

export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
}
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};
/**
 * use Authorized check all menu item
 */

const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] =>
  menuList.map((item) => {
    const localItem = { ...item, children: item.children ? menuDataRender(item.children) : [] };
    return Authorized.check(item.authority, localItem, null) as MenuDataItem;
  });

const defaultFooterDom = (
  <DefaultFooter
    copyright="2019 蚂蚁金服体验技术部出品"
    links={[
      {
        key: 'Ant Design Pro',
        title: 'Ant Design Pro',
        href: 'https://pro.ant.design',
        blankTarget: true,
      },
      {
        key: 'github',
        title: <GithubOutlined />,
        href: 'https://github.com/ant-design/ant-design-pro',
        blankTarget: true,
      },
      {
        key: 'Ant Design',
        title: 'Ant Design',
        href: 'https://ant.design',
        blankTarget: true,
      },
    ]}
  />
);

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const {
    dispatch,
    children,
    settings,
    route,
    location = {
      pathname: '/',
    },
  } = props;
  /**
   * constructor
   */
  // const newTabIndex = 0;
  const updateTree = data => {
    const treeData = data;
    const treeList = [];
    // 递归获取树列表
    const getTreeList = data => {
      data.forEach(node => {
        if (node.component) {
          treeList.push({ tab: node.name, key: node.path, locale: node.locale, closable: true, component: node.component });
        }
        if (node.routes && node.routes.length > 0) { //!node.hideChildrenInMenu &&
          getTreeList(node.routes);
        }
      });
    };
    getTreeList(treeData);
    return treeList;
  };
  let [menuItemProps,setMenuItemProps] = useState({})
  const {routes} = props.route;
  const tabLists = updateTree(routes), routeKey = '/welcome', tabName = '首页';
  console.log("tabLists", tabLists)
  let [panes, setPanes] = useState([tabLists[0]]);// 对应他框架里的tabList
  let tabListArr = [];
  // tabLists.map((v) => {
  //   if (v.key === routeKey) {
  //     if (panes.length === 0) {
  //       v.closable = false
  //       v.tab = tabName
  //       setPanes(panes.push(v))

  //     }
  //   }
  //   if (v.key) {
  //     tabListArr.push(v.key)
  //   }
  // });
  let [newTabIndex, setNewTabIndex] = useState(0);
  let [lastIndex, setLastIndex] = useState(0);

  let [activeKey, setActiveKey] = useState(panes[0].key);
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
  }, []);
  /**
   * init variables
   */

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  }; // get children authority

  const authorized = getAuthorityFromRouter(props.route.routes, location.pathname || '/') || {
    authority: undefined,
  };
  const { formatMessage } = useIntl();

  /**
   * some function
   */

  const onChange = (activeKey: React.SetStateAction<string>) => {
    setActiveKey(activeKey);
    history.push(activeKey)
  };

  const onEdit = (targetKey: any, action: React.ReactText) => {
    if (action == 'remove') {
      remove(targetKey)
    }

  };

  const add = (newPage) => {
    let obj = {}
    tabLists.map((v) => {
      if (v.key === newPage.pathname) {
        obj = v
      }
      
    });
    // tab: node.name, key: node.path, locale: node.locale, closable: true, component: node.component
    const { key, tab, component } = obj;
    let isPush = true;
    panes.forEach((item) => {
      if (item.key === key) {
        isPush = false;// 不新增tab，但是需要高亮点击的tab
        setActiveKey(key)
      }
    })
    if (isPush) {
      setNewTabIndex(newTabIndex + 1)
      // const activeKey = `newTab${newTabIndex}`;
      panes.push({ key, tab, path:key,component });
      setPanes(panes)
      setActiveKey(key)
      history.push(key)
    }
  };

  const remove = (targetKey: string) => {
    console.log(targetKey,'targetKey')
    let index = 0;
    panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        setLastIndex(i - 1)
        index = i-1;
      }
    });
    const paness = panes.filter(pane => pane.key !== targetKey);
    if (paness.length && activeKey === targetKey) {
      if (lastIndex >= 0) {
        activeKey = paness[index].key;
      } else {
        activeKey = paness[0].key;
      }
    }
    setPanes(paness)
    setActiveKey(activeKey)
    history.push(activeKey)
   
  };
  return (
    <ProLayout
      logo={logo}
      formatMessage={formatMessage}
      menuHeaderRender={(logoDom, titleDom) => (
        <Link to="/">
          {logoDom}
          {titleDom}
        </Link>
      )}
      onPageChange={(newPage)=>{
        add(newPage)
      }}
      onCollapse={handleMenuCollapse}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl || menuItemProps.children || !menuItemProps.path) {
          return defaultDom;
        }
        
        return <Link to={menuItemProps.path} >{defaultDom}</Link>;// 侧边菜单栏的单独item，link对应渲染children
      }}
      
      breadcrumbRender={(routers = []) => [
        {
          path: '/',
          breadcrumbName: formatMessage({ id: 'menu.home' }),
        },
        ...routers,
      ]}
      itemRender={(route, params, routes, paths) => {
        const first = routes.indexOf(route) === 0;
        return first ? (
          <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        ) : (
            <span>{route.breadcrumbName}</span>
          );
      }}
      // footerRender={() => defaultFooterDom}
      menuDataRender={menuDataRender}
      rightContentRender={() => <RightContent />}
      {...props}
      {...settings}
    >
      <div>
        <Tabs
          hideAdd
          onChange={onChange}
          activeKey={activeKey}
          type="editable-card"
          onEdit={onEdit}
        >
          {panes.map(pane => (
            <TabPane tab={pane.tab} key={pane.key} closable={pane.closable}>
              <Authorized authority={authorized!.authority} noMatch={noMatch}>
                {/* {children} */}
                <Route key={pane.key} path={pane.key} component={pane.component} exact={pane.exact} />
              </Authorized>
            </TabPane>
          ))}
        </Tabs>
      </div>

    </ProLayout>
  );
};

export default connect(({ global, settings }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
}))(BasicLayout);
